<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo List</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            background-color: #f5f5f5;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1 {
            text-align: center;
            margin-bottom: 30px;
            color: #2c3e50;
        }
        .task-form {
            display: flex;
            margin-bottom: 30px;
            gap: 10px;
        }
        .task-input {
            flex: 1;
            padding: 12px 15px;
            font-size: 16px;
            border: 2px solid #3498db;
            border-radius: 4px;
            outline: none;
            transition: border-color 0.3s;
        }
        .task-input:focus {
            border-color: #2980b9;
        }
        .add-btn {
            padding: 12px 25px;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background 0.3s;
        }
        .add-btn:hover {
            background: #2980b9;
        }
        .task-list {
            list-style: none;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        .task-item {
            display: flex;
            align-items: center;
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            transition: background 0.2s;
        }
        .task-item:hover {
            background: #f9f9f9;
        }
        .task-checkbox {
            margin-right: 15px;
            transform: scale(1.3);
            cursor: pointer;
        }
        .task-title {
            flex: 1;
            font-size: 18px;
            word-break: break-word;
        }
        .completed {
            text-decoration: line-through;
            color: #95a5a6;
        }
        .task-actions {
            display: flex;
            gap: 10px;
        }
        .edit-btn, .delete-btn {
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: opacity 0.3s;
        }
        .edit-btn {
            background: #f39c12;
            color: white;
        }
        .delete-btn {
            background: #e74c3c;
            color: white;
        }
        .edit-btn:hover, .delete-btn:hover {
            opacity: 0.9;
        }
        .task-edit {
            flex: 1;
            padding: 10px 15px;
            font-size: 18px;
            border: 2px solid #3498db;
            border-radius: 4px;
            outline: none;
        }
        .save-btn {
            background: #2ecc71;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
        }
        .no-tasks {
            text-align: center;
            padding: 30px;
            color: #7f8c8d;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>我的待办事项</h1>
        <div class="task-form">
            <input type="text" class="task-input" placeholder="输入新任务..." autofocus>
            <button class="add-btn">添加任务</button>
        </div>
        <ul class="task-list" id="taskList">
            <div class="no-tasks">暂无任务，添加你的第一个任务吧</div>
        </ul>
    </div>

    <script>
        // DOM元素
        const taskInput = document.querySelector('.task-input');
        const addButton = document.querySelector('.add-btn');
        const taskList = document.getElementById('taskList');

        // API基础URL
        const API_BASE_URL = 'http://localhost:5000/tasks';

        // 显示加载状态
        const showLoading = () => {
            taskList.innerHTML = '<div class="no-tasks">加载中...</div>';
        };

        // 显示空状态
        const showEmpty = () => {
            taskList.innerHTML = '<div class="no-tasks">暂无任务，添加你的第一个任务吧</div>';
        };

        // 获取所有任务
        const fetchTasks = async () => {
            showLoading();
            try {
                const response = await fetch(API_BASE_URL);
                if (!response.ok) throw new Error('获取任务失败');
                const tasks = await response.json();

                if (tasks.length === 0) {
                    showEmpty();
                    return [];
                }

                return tasks;
            } catch (error) {
                console.error('获取任务失败:', error);
                taskList.innerHTML = '<div class="no-tasks">获取任务失败，请刷新重试</div>';
                return [];
            }
        };

        // 创建任务项DOM
        const createTaskElement = (task) => {
            const li = document.createElement('li');
            li.className = 'task-item';
            li.dataset.id = task.id;

            li.innerHTML = `
                <input type="checkbox" class="task-checkbox" ${task.completed ? 'checked' : ''}>
                <div class="task-title ${task.completed ? 'completed' : ''}">${task.title}</div>
                <div class="task-actions">
                    <button class="edit-btn">编辑</button>
                    <button class="delete-btn">删除</button>
                </div>
            `;

            return li;
        };

        // 渲染任务列表
        const renderTasks = async () => {
            const tasks = await fetchTasks();
            if (tasks.length === 0) return;

            taskList.innerHTML = '';
            tasks.forEach(task => {
                const taskElement = createTaskElement(task);
                taskList.appendChild(taskElement);

                // 添加复选框事件
                const checkbox = taskElement.querySelector('.task-checkbox');
                checkbox.addEventListener('change', () => toggleTaskStatus(task.id, checkbox.checked));

                // 添加删除按钮事件
                const deleteBtn = taskElement.querySelector('.delete-btn');
                deleteBtn.addEventListener('click', () => deleteTask(task.id));

                // 添加编辑按钮事件
                const editBtn = taskElement.querySelector('.edit-btn');
                editBtn.addEventListener('click', () => enableTaskEdit(taskElement, task));
            });
        };

        // 添加新任务
        const addNewTask = async () => {
            const title = taskInput.value.trim();
            if (!title) {
                alert('任务标题不能为空');
                return;
            }

            try {
                const response = await fetch(API_BASE_URL, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ title })
                });

                if (!response.ok) throw new Error('添加任务失败');

                taskInput.value = '';
                taskInput.focus();
                renderTasks();
            } catch (error) {
                console.error('添加任务失败:', error);
                alert('添加任务失败，请重试');
            }
        };

        // 切换任务状态
        const toggleTaskStatus = async (id, completed) => {
            try {
                const response = await fetch(`${API_BASE_URL}/${id}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ completed })
                });

                if (!response.ok) throw new Error('更新状态失败');

                renderTasks();
            } catch (error) {
                console.error('更新状态失败:', error);
                alert('更新任务状态失败，请重试');
            }
        };

        // 删除任务
        const deleteTask = async (id) => {
            if (!confirm('确定要删除这个任务吗？')) return;

            try {
                const response = await fetch(`${API_BASE_URL}/${id}`, {
                    method: 'DELETE'
                });

                if (!response.ok) throw new Error('删除任务失败');

                renderTasks();
            } catch (error) {
                console.error('删除任务失败:', error);
                alert('删除任务失败，请重试');
            }
        };

        // 启用任务编辑
        const enableTaskEdit = (taskElement, task) => {
            const titleElement = taskElement.querySelector('.task-title');
            const originalTitle = titleElement.textContent;

            taskElement.innerHTML = `
                <input type="text" class="task-edit" value="${originalTitle}">
                <button class="save-btn">保存</button>
                <button class="delete-btn">取消</button>
            `;

            const editInput = taskElement.querySelector('.task-edit');
            const saveBtn = taskElement.querySelector('.save-btn');
            const cancelBtn = taskElement.querySelector('.delete-btn');

            editInput.focus();
            editInput.select();

            // 保存编辑
            saveBtn.addEventListener('click', async () => {
                const newTitle = editInput.value.trim();
                if (!newTitle) {
                    alert('任务标题不能为空');
                    return;
                }

                if (newTitle !== originalTitle) {
                    try {
                        const response = await fetch(`${API_BASE_URL}/${task.id}`, {
                            method: 'PUT',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ title: newTitle })
                        });

                        if (!response.ok) throw new Error('更新任务失败');
                    } catch (error) {
                        console.error('更新任务失败:', error);
                        alert('更新任务失败，请重试');
                    }
                }

                renderTasks();
            });

            // 取消编辑
            cancelBtn.addEventListener('click', () => {
                renderTasks();
            });
        };

        // 事件监听
        addButton.addEventListener('click', addNewTask);
        taskInput.addEventListener('keyup', e => {
            if (e.key === 'Enter') addNewTask();
        });

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            renderTasks();
        });
    </script>
</body>
</html>